package com.shujia.flink.state;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Demo2Checkpoint {
    public static void main(String[] args) throws Exception {
        //1、创建flink执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();


        /*
         * checkpoint：定时将flink计算的状态持久化到HDFS,如果任务执行失败可以基于HDFS中保存的状态恢复任务，保证状态不丢失不丢失
         *
         * 开启checkpoint
         */
        // 每 10000ms 开始一次 checkpoint
//        env.enableCheckpointing(10000);
//
//        // 使用 externalized checkpoints，这样 checkpoint 在作业取消后仍就会被保留
//        env.getCheckpointConfig().setExternalizedCheckpointCleanup(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
//
//        //将状态保存到hdfs中
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://master:9000/file/checkpoint");
//
//        //状态再flink中保存的位置
//        //HashMapStateBackend:将状态保存再flink的内存中
//        env.setStateBackend(new HashMapStateBackend());


        //2、读取数据，nc -lk 8888  --无界流
        DataStream<String> linesDS = env.socketTextStream("master", 8888);
        //lambda表达式
        DataStream<String> wordsDS = linesDS.flatMap((line, out) -> {
            //将一行切分成一个数组
            String[] split = line.split(",");
            //循环将数据发生到下游
            for (String word : split) {
                //将数据发送到下游
                out.collect(word);
            }
        }, Types.STRING);//指定返回的类型信息

        //转换成kv格式
        //Types.TUPLE(Types.STRING, Types.INT) 指定返回的类型
        DataStream<Tuple2<String, Integer>> kvDS = wordsDS
                .map(word -> Tuple2.of(word, 1), Types.TUPLE(Types.STRING, Types.INT));

        //安装单词进行分组
        KeyedStream<Tuple2<String, Integer>, String> keyByDS = kvDS.keyBy(kv -> kv.f0);

        //统计单词的数量
        DataStream<Tuple2<String, Integer>> countDS = keyByDS.sum(1);
        //打印结果
        countDS.print();
        //启动flink
        env.execute();
    }
}
